package com.zhao.dota.common.task;

import com.zhao.dota.util.RedisDistributedLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.util.UUID;

@Slf4j
public abstract class BaseTask implements Runnable {

    private static final String KEY = "task";

    private static final String DELIMITER = ":";
    @Value("${use-redis:false}")
    private boolean userRedis;

    protected abstract void execute();

    protected abstract String getKey();

    @Override
    public void run() {
        String key = String.join(DELIMITER, KEY, getKey());
        String requestId = tryLock(key);
        if (requestId == null) {
            return;
        }
        try {
            execute();
        } catch (Exception e) {
            log.error("定时任务执行失败, key:" + key, e);
        } finally {
            releaseLock(key, requestId);
        }
    }

    private String tryLock(String key) {
        String requestId = UUID.randomUUID().toString().replace("-", "");
        if (userRedis) {
            boolean b = RedisDistributedLockUtil.distributedLock(key, requestId, 60);
            if (b) {
                if (log.isInfoEnabled()) {
                    log.info("线程[{}]获取到锁，key为: {}", Thread.currentThread().getName(), key);
                }
            } else {
                return null;
            }
        }
        return requestId;
    }

    private void releaseLock(String key, String requestId) {
        if (userRedis) {
            RedisDistributedLockUtil.distributedUnLock(key, requestId);
        }
    }

}
